using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement.Return;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement.Return
{
    /// <summary>
    /// 获取退货通知单列表查询处理器
    /// </summary>
    public class GetReturnNoticeListHandler : IRequestHandler<GetReturnNoticeListCommand, APIResult<GetReturnNoticeListDto>>
    {
        private readonly RBACDbContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public GetReturnNoticeListHandler(RBACDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 处理获取退货通知单列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>退货通知单列表结果</returns>
        public async Task<APIResult<GetReturnNoticeListDto>> Handle(GetReturnNoticeListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建基础查询
                var query = _dbContext.Set<ReturnNotice>()
                    .Where(r => !r.IsDeleted)
                    .AsQueryable();

                // 应用搜索条件
                if (!string.IsNullOrWhiteSpace(request.BillCode))
                {
                    query = query.Where(r => r.BillCode != null && r.BillCode.Contains(request.BillCode));
                }

                if (!string.IsNullOrWhiteSpace(request.CustomerName))
                {
                    query = query.Where(r => r.CustomerName != null && r.CustomerName.Contains(request.CustomerName));
                }

                if (!string.IsNullOrWhiteSpace(request.SalesPerson))
                {
                    query = query.Where(r => r.Operator != null && r.Operator.Contains(request.SalesPerson));
                }

                if (!string.IsNullOrWhiteSpace(request.BillStatus))
                {
                    query = query.Where(r => r.BillStatus == request.BillStatus);
                }

                if (!string.IsNullOrWhiteSpace(request.BusinessStatus))
                {
                    query = query.Where(r => r.BusinessStatus == request.BusinessStatus);
                }

                if (request.StartDate.HasValue)
                {
                    query = query.Where(r => r.BillDate >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    query = query.Where(r => r.BillDate <= request.EndDate.Value.Date.AddDays(1).AddTicks(-1));
                }

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页查询
                var returnNotices = await query
                    .OrderByDescending(r => r.CreateTime)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 转换为DTO
                var returnNoticeDtos = new List<ReturnNoticeDto>();
                foreach (var notice in returnNotices)
                {
                    // 获取物料数量
                    var materialCount = await _dbContext.Set<ReturnMaterials>()
                        .Where(m => m.ReturnNoticeId == notice.Id && !m.IsDeleted)
                        .CountAsync(cancellationToken);

                    var dto = new ReturnNoticeDto
                    {
                        Id = notice.Id,
                        BillCode = notice.BillCode,
                        BusinessType = notice.BusinessType,
                        CustomerName = notice.CustomerName,
                        Warehouse = notice.Warehouse,
                        BillDate = notice.BillDate,
                        Operator = notice.Operator,
                        SalesPerson = notice.Operator, // 使用操作员作为销售员
                        BillStatus = notice.BillStatus,
                        Reviewer = notice.Reviewer,
                        ReturnReason = notice.ReturnReason,
                        BusinessStatus = notice.BusinessStatus,
                        ReviewDate = notice.ReviewDate,
                        ProcessingMethod = notice.ProcessingMethod,
                        Status = notice.Status,
                        CreateTime = notice.CreateTime,
                        MaterialCount = materialCount
                    };

                    returnNoticeDtos.Add(dto);
                }

                var result = new GetReturnNoticeListDto
                {
                    PageDatas = returnNoticeDtos,
                    TotalCount = totalCount
                };

                return new APIResult<GetReturnNoticeListDto>
                {
                    Code = APIEnums.Success,
                    Msg = "获取退货通知单列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new APIResult<GetReturnNoticeListDto>
                {
                    Code = APIEnums.Fail,
                    Msg = "获取退货通知单列表失败：" + ex.Message,
                    Data = new GetReturnNoticeListDto()
                };
            }
        }
    }
}